package com.gz.steak.modules.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.gz.steak.common.aspect.anotation.LoginLog;
import com.gz.steak.common.web.base.BaseController;
import com.gz.steak.common.exception.BusinessException;
import com.gz.steak.common.exception.EmBusinessError;
import com.gz.steak.modules.system.pojo.model.LoginModel;
import com.gz.steak.utils.ip.IPUtil;
import com.gz.steak.utils.jwt.JWTUtil;
import com.gz.steak.utils.security.SpringSecurityUtil;
import com.gz.steak.utils.validator.ValidatorUtil;
import com.gz.steak.common.web.result.Result;
import com.gz.steak.modules.system.service.SysLoginService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 刘牌
 * @Date 2020/2/22 0022 12:35
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class SysLoginController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(SysLoginController.class);

    @Autowired
    private SysLoginService loginService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private Producer producer;
    @Autowired
    private HttpServletRequest request;
    //全局保存用户名和用户客户端信息
    private Map<String, String> map = new HashMap<>();

    /**
     * 生成校验码
     * @param response
     * @throws IOException
     */
    @GetMapping("captcha.jpg")
    public void captcha( HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Content","no-store,nocache");
        response.setContentType("image/jpeg");
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,text);
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"jpg",outputStream);
        IOUtils.closeQuietly(outputStream);
    }
    /**
     * 用户注册，规定注册用户拥有查看所有菜单的权限，即role = 1
     * @param username
     * @param password
     * @return
     * @throws BusinessException
     */
    @PostMapping("/register")
    public Result register(@RequestParam String username,@RequestParam String password,@RequestParam String address) throws BusinessException {
        String ip = IPUtil.getIpAddress(request);
        if (username.isEmpty() || password.isEmpty()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        return Result.success("success");
    }

    /**
     * 登陆验证
     * @return
     */
    @LoginLog
    @PostMapping("/login")
    public Result Login(@RequestBody LoginModel loginModel) throws BusinessException{
        Object captchaSession = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        request.getSession().setAttribute("username",loginModel.getUserName());
        String s = request.getHeader("user-agent");//客户端信息
        //将登陆的用户和客户端信息保存
        map.put("userAgent::" + loginModel.getUserName(), s);
        if (loginModel.getUserName().isEmpty() || loginModel.getUserPassword().isEmpty()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        if (!captchaSession.equals(loginModel.getCaptcha())){
            throw new BusinessException(EmBusinessError.CAPTCHA_ERROR);
        }
        LoginModel userInfo = loginService.getUserInfo(loginModel.getUserName());
        if (!SpringSecurityUtil.check(loginModel,userInfo.getUserPassword())) {
            throw new BusinessException(EmBusinessError.PASSWORD_ERROR);
        }
        //设置token过期时间为7个小时
        String token = JWTUtil.createJWT(25200000, userInfo);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", token);
        return Result.success(jsonObject);
    }

    /**
     * 根据token获取用户信息
     * @param
     * @return
     * @throws BusinessException
     */
    @GetMapping("getUserInfo")
    public Result getUserInfo(HttpServletRequest request) throws BusinessException {
        String token = request.getHeader("token");
        String userAgent = request.getHeader("user-agent");
        String username = JWT.decode(token).getClaim("username").asString();
        LoginModel userInfo = loginService.getUserInfo(username);
        if (!JWTUtil.checkJWT(token,userInfo)){
           throw new BusinessException(EmBusinessError.IDENTITY_EXPIRED);
        }else {
            if (!ValidatorUtil.isEmpty(map)) {
                if (!(map.get("userAgent::" + username)).equals(userAgent)) {
                    //别处登陆
                    throw new BusinessException(EmBusinessError.USER_LOGIN_IN_ANOTHER);
                } else {
                    return Result.success(userInfo);
                }
            } else {
                map.put("userAgent::" + username, userAgent);
                return Result.success(userInfo);
            }
        }

    }

}
